﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyTruongHoc_App.MyDataSet;
using QuanLyTruongHoc_App.MyDataSet.QLTHTableAdapters;
using System.Configuration;

namespace QuanLyTruongHoc_App
{
    public partial class BangDiemTN : Form
    {
        public const String CLN_TOT_NGHIEP = "Tốt nghiệp";
        
        protected DataTable data;
        protected List<int> lIdMonHoc;
        protected List<float> lHSMonHoc;
        protected int state,
                    diemCol;

        protected DataGridViewComboBoxColumn grc_TotNghiep;
        protected BindingSource tblBinding;

        
        public BangDiemTN()
        {
            InitializeComponent();
            lIdMonHoc = new List<int>();
            lHSMonHoc = new List<float>();
            dg_DanhSach.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dg_DanhSach_DataBindingComplete);
        }

        private void QuanLyGiaoVien_Load(object sender, EventArgs e)
        {
            refreshData();
        }

        private void checkUserPower()
        {
            // --------------------------------
            int pow = PublicLib.getUserPower(PConst.QUYEN_QL_DIEM_TOT_NGHIEP);
            // edit
            tsb_Luu.Enabled = ((pow & PConst.POW_EDIT) > 0);
            //dg_DanhSach.ReadOnly = !tsb_Luu.Enabled;
            for (int i = diemCol; i < dg_DanhSach.ColumnCount; i++)
                dg_DanhSach.Columns[i].ReadOnly = !tsb_Luu.Enabled;
        }

        private void reloadComboBox()
        {
            state = PConst.STATE_LOAD;
            // Lop
            MyDataSet.QLTHTableAdapters.tbl_LopHocTableAdapter lopAdap = new tbl_LopHocTableAdapter();
            lopAdap.Connection.ConnectionString = PublicLib.getStrConn();
            lopAdap.FillByLopKeTiep(qLTH.tbl_LopHoc, PConst.FLAG_LOP_TOT_NGHIEP);

            tscb_Lop.Items.Clear();
            for (int i = 0; i < qLTH.tbl_LopHoc.Rows.Count; i++)
            {
                tscb_Lop.Items.Add(qLTH.tbl_LopHoc.Rows[i][qLTH.tbl_LopHoc.TenLopColumn].ToString());
            }
            tscb_Lop.Items.Add(MSG.MNU_ALL);
            tscb_Lop.SelectedIndex = tscb_Lop.Items.Count - 1; // All
            // --------------
            // Nam Hoc
            MyDataSet.QLTHTableAdapters.tbl_NamHocTableAdapter namAdap = new tbl_NamHocTableAdapter();
            namAdap.Connection.ConnectionString = PublicLib.getStrConn();
            namAdap.FillByFlag(qLTH.tbl_NamHoc, PConst.FLAG_NONE);

            tscb_NamHoc.Items.Clear();
            for (int i = 0; i < qLTH.tbl_NamHoc.Rows.Count; i++)
            {
                tscb_NamHoc.Items.Add(qLTH.tbl_NamHoc.Rows[i][qLTH.tbl_NamHoc.TenColumn].ToString());
            }

            if (tscb_NamHoc.Items.Count > 1)
                tscb_NamHoc.SelectedIndex = tscb_NamHoc.Items.Count - 2;
            // --------------
            state = PConst.STATE_LOADED;
        }

        private void reloadDataTable()
        {
            if (tscb_Lop.SelectedIndex == -1) return;
            
            int idNamHoc = (int)qLTH.tbl_NamHoc[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn];
            data = new DataTable();
            // Add Ten Hoc Sinh column
            data.Columns.Add(qLTH.tbl_HocSinh.idColumn.ColumnName, Type.GetType("System.Int32"));
            data.Columns.Add(qLTH.tbl_HocSinh.HoDemColumn.ColumnName, Type.GetType("System.String"));
            data.Columns.Add(qLTH.tbl_HocSinh.TenColumn.ColumnName, Type.GetType("System.String"));
            data.Columns.Add(qLTH.tbl_HocSinh.GioiTinhColumn.ColumnName, Type.GetType("System.String"));
            data.Columns.Add(qLTH.tbl_HocSinh.NgaySinhColumn.ColumnName, Type.GetType("System.DateTime"));
            // ---------
            // Add Mon Hoc
            tbl_MonHocTableAdapter monAdap = new tbl_MonHocTableAdapter();
            monAdap.Connection.ConnectionString = PublicLib.getStrConn();
            monAdap.Fill(qLTH.tbl_MonHoc);

            qh_MonThiTNTableAdapter monThiAdap = new qh_MonThiTNTableAdapter();
            monThiAdap.Connection.ConnectionString = PublicLib.getStrConn();
            monThiAdap.ClearBeforeFill = true;
            monThiAdap.FillByNamHoc(qLTH.qh_MonThiTN, idNamHoc);

            lIdMonHoc.Clear();
            lHSMonHoc.Clear();
            for (int i = 0; i < qLTH.qh_MonThiTN.Rows.Count; i++)
            {
                DataRow[] tmp = qLTH.tbl_MonHoc.Select(qLTH.tbl_MonHoc.idColumn.ColumnName + "=" + qLTH.qh_MonThiTN.Rows[i][qLTH.qh_MonThiTN.idMonHocColumn].ToString());
                if (tmp.Length > 0)
                {
                    data.Columns.Add(tmp[0][qLTH.tbl_MonHoc.TenMonHocColumn].ToString(), // + " (x" +
                                     //qLTH.qh_MonThiTN.Rows[i][qLTH.qh_MonThiTN.HeSoColumn].ToString() + ")",
                                     Type.GetType("System.Single")); //float
                    lIdMonHoc.Add((int)qLTH.qh_MonThiTN.Rows[i][qLTH.qh_MonThiTN.idMonHocColumn]);
                    //lHSMonHoc.Add(float.Parse(qLTH.qh_MonThiTN.Rows[i][qLTH.qh_MonThiTN.HeSoColumn].ToString()));
                }
            }
            // Diem TB cac mon
            data.Columns.Add(MSG.MNU_TB_CA_KY, Type.GetType("System.Single"));
            // Tot nghiep
            data.Columns.Add(CLN_TOT_NGHIEP, Type.GetType("System.Int32"));
            // ---------
            tblBinding = new BindingSource();

            dg_DanhSach.DataSource = tblBinding;
            tblBinding.DataSource = data;

            dg_DanhSach.Columns.Clear();
            dg_DanhSach.Columns.Add("grc_stt", "STT");

            for (int i = 0; i < data.Columns.Count - 1; i++)
            {
                dg_DanhSach.Columns.Add(data.Columns[i].ColumnName, data.Columns[i].ColumnName);
                dg_DanhSach.Columns[dg_DanhSach.ColumnCount - 1].DataPropertyName = data.Columns[i].ColumnName;
            }

            dg_DanhSach.Columns[0].Width = 40;

            dg_DanhSach.Columns[1].Visible = false; //id
            dg_DanhSach.Columns[2].HeaderText = "Họ Đệm";
            dg_DanhSach.Columns[3].HeaderText = "Tên";
            dg_DanhSach.Columns[3].Width = 60;
            dg_DanhSach.Columns[4].HeaderText = "Giới Tính";
            dg_DanhSach.Columns[4].Width = 60;
            dg_DanhSach.Columns[5].HeaderText = "Ngày Sinh";
            dg_DanhSach.Columns[5].DefaultCellStyle.Format = "dd/MM/yyyy";
            dg_DanhSach.Columns[5].Width = 75;

            diemCol = 6; // them cot gioi tinh
 
            dg_DanhSach.Columns[0].Width = 40;
            for (int i = diemCol; i < dg_DanhSach.ColumnCount; i++)
                dg_DanhSach.Columns[i].Width = 45;

            grc_TotNghiep = new DataGridViewComboBoxColumn();
            
            // add 
            dg_DanhSach.Columns.Add(grc_TotNghiep);
            // -------------------------------

            grc_TotNghiep.HeaderText = "Tốt nghiệp";
            grc_TotNghiep.Name = "grc_TotNghiep";
            grc_TotNghiep.DataPropertyName = CLN_TOT_NGHIEP;
            grc_TotNghiep.Width = 150;
            // ----------------------
            tbl_HinhThucTNTableAdapter tnAdap = new tbl_HinhThucTNTableAdapter();
            tnAdap.Connection.ConnectionString = PublicLib.getStrConn();
            tnAdap.Fill(qLTH.tbl_HinhThucTN);

            grc_TotNghiep.DataSource = qLTH.tbl_HinhThucTN;
            grc_TotNghiep.DisplayMember = qLTH.tbl_HinhThucTN.TenColumn.ColumnName;
            grc_TotNghiep.ValueMember = qLTH.tbl_HinhThucTN.idColumn.ColumnName;
            //grc_LenLop.ReadOnly = true; // Chi de view ket qua hoc tap, ko xet len lop tai day

            for (int i = 0; i < diemCol; i++)
                dg_DanhSach.Columns[i].ReadOnly = true;

            dg_DanhSach.Columns[dg_DanhSach.ColumnCount - 2].ReadOnly = true;
            fillData();
        }

        private void fillData()
        {
            if (state == PConst.STATE_LOAD) return;
            if (tscb_Lop.SelectedIndex == -1) return;

            int idNamHoc = (int)qLTH.tbl_NamHoc[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn];
            tbl_HocSinhTableAdapter hsAdap = new tbl_HocSinhTableAdapter();
            hsAdap.Connection.ConnectionString = PublicLib.getStrConn();
            hsAdap.ClearBeforeFill = true;

            qh_DiemTNTableAdapter diemAdp = new qh_DiemTNTableAdapter();
            diemAdp.Connection.ConnectionString = PublicLib.getStrConn();
            diemAdp.ClearBeforeFill = true;

            qh_DSThiTotNghiepTableAdapter dsTN = new qh_DSThiTotNghiepTableAdapter();
            dsTN.Connection.ConnectionString = PublicLib.getStrConn();
            dsTN.FillByNamHoc(qLTH.qh_DSThiTotNghiep, idNamHoc);

            if (tscb_Lop.SelectedIndex != tscb_Lop.Items.Count - 1)
            {
                int idLop = int.Parse(qLTH.tbl_LopHoc.Rows[tscb_Lop.SelectedIndex][qLTH.tbl_LopHoc.idColumn].ToString());
                hsAdap.FillByLopHSTotNghiep(qLTH.tbl_HocSinh, idNamHoc, idLop);
            }
            else
            {
                // all
                hsAdap.FillByHSTotNghiep(qLTH.tbl_HocSinh, idNamHoc);
            }

            data.Rows.Clear();
            diemAdp.FillByNamHoc(qLTH.qh_DiemTN, idNamHoc);

            for (int i = 0; i < qLTH.tbl_HocSinh.Rows.Count; i++)
            {
                DataRow nRow = data.NewRow();
                int idHS = (int)qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.idColumn];
                nRow[0] = idHS; // id
                nRow[1] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.HoDemColumn]; // Ho Dem
                nRow[2] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.TenColumn]; // Ten
                int gt = int.Parse(qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.GioiTinhColumn].ToString()); // Ho Dem
                nRow[3] = (gt == 0 ? "Nam" : "Nữ");
                nRow[4] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.NgaySinhColumn]; // Ten

                for (int j = diemCol - 1; j < data.Columns.Count - 2; j++)
                {
                    DataRow[] tmpRow = qLTH.qh_DiemTN.Select(qLTH.qh_DiemTN.idMonHocColumn.ColumnName + "=" + lIdMonHoc[j - diemCol + 1] + 
                                                             " AND " + 
                                                             qLTH.qh_DiemTN.idHocSinhColumn.ColumnName + "=" + idHS);
                    if (tmpRow.Length > 0)
                        nRow[j] = tmpRow[0][qLTH.qh_DiemTN.DiemColumn];
                }

                /*DataRow[] tmp = qLTH.qh_DSThiTotNghiep.Select(qLTH.qh_DSThiTotNghiep.idHocSinhColumn.ColumnName + "=" + idHS);
                if (tmp.Length > 0)
                    nRow[data.Columns.Count - 1] = tmp[0][qLTH.qh_DSThiTotNghiep.KetQuaColumn]; //ket qua thi
                else
                    nRow[data.Columns.Count - 1] = DBNull.Value;*/
                data.Rows.Add(nRow);
            }
            
            // Sort
            dg_DanhSach.Sort(dg_DanhSach.Columns[3], ListSortDirection.Ascending);
            dg_DanhSach.Columns[3].HeaderCell.SortGlyphDirection = SortOrder.Ascending;

            calculateData();
            
            for (int i = 0; i < data.Rows.Count; i++)
            {
                int idHS = (int)data.Rows[i][0];
                DataRow[] tmp = qLTH.qh_DSThiTotNghiep.Select(qLTH.qh_DSThiTotNghiep.idHocSinhColumn.ColumnName + "=" + idHS);
                if (tmp.Length > 0 && (tmp[0][qLTH.qh_DSThiTotNghiep.KetQuaColumn] != DBNull.Value)) 
                    data.Rows[i][data.Columns.Count - 1] = tmp[0][qLTH.qh_DSThiTotNghiep.KetQuaColumn]; //ket qua thi
                //else
                //    data.Rows[i][data.Columns.Count - 1] = DBNull.Value;
            }
        }

        private void refreshData()
        {
            reloadData();
            reloadComboBox();
            reloadDataTable();
        }

        private void QuanLyGiaoVien_Resize(object sender, EventArgs e)
        {
            dg_DanhSach.Width = this.Width - 5;
            dg_DanhSach.Height = stt_Bottom.Top - dg_DanhSach.Top - 1;
        }

        private void dg_DanhSach_DataBindingComplete(object sender, EventArgs e)
        {
            reloadData();
        }

        private void reloadData()
        {
            for (int i = 0; i < dg_DanhSach.RowCount; i++)
            {
                dg_DanhSach.Rows[i].Cells[0].Value = i + 1;
                dg_DanhSach.Rows[i].DefaultCellStyle.BackColor = (i % 2 == 1) ? PConst.COLOR_BACK_1 : PConst.COLOR_BACK_DEF;
            }
        }

        private void tscb_Lop_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (state == PConst.STATE_LOAD)
                return;

            fillData();
            //reloadDataTable();
        }

        private void calculateData()
        {
            for (int i = 0; i < data.Rows.Count; i++)
            {
                float result = 0;
                int _under5 = 0;
                float dv = 0;
                float diemMin = 1000;
                int j;

                for (j = diemCol - 1; j < data.Columns.Count - 2; j++)
                {
                    if (data.Rows[i][j] != DBNull.Value)
                    { 
                        // ko tinh truong hop = null vi co the mon do ko duoc thi TN
                        float tmp = 0;
                        tmp = (float)data.Rows[i][j];
                        result += (tmp); // * lHSMonHoc[j - diemCol + 1]);
                        dv += 1; //lHSMonHoc[j - diemCol + 1];
                        if (tmp < diemMin) diemMin = tmp;
                        if (tmp < 5) _under5++;
                    }
                }

                if (dv != 0)
                   result = result / dv;

                data.Rows[i][j] = result.ToString(PConst.LAM_TRON);
                data.Rows[i][j + 1] = PublicLib.XetTotNghiep(diemMin, _under5, result);
            }
        }

        private void tsb_TinhDiemTB_Click(object sender, EventArgs e)
        {
            //calculateData();
        }

        private void tscb_NamHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tscb_NamHoc.SelectedIndex == -1)
                return;
            reloadDataTable();
        }

        private void saveData()
        {
            int idNamHoc = (int)qLTH.tbl_NamHoc[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn];
            qh_DiemTNTableAdapter diemAdap = new qh_DiemTNTableAdapter();
            diemAdap.Connection.ConnectionString = PublicLib.getStrConn();
            diemAdap.FillByNamHoc(qLTH.qh_DiemTN, idNamHoc);

            qh_DSThiTotNghiepTableAdapter dsTN = new qh_DSThiTotNghiepTableAdapter();
            dsTN.Connection.ConnectionString = PublicLib.getStrConn();
            dsTN.FillByNamHoc(qLTH.qh_DSThiTotNghiep, idNamHoc);

            tbl_HocSinhTableAdapter hsAdap = new tbl_HocSinhTableAdapter();
            hsAdap.Connection.ConnectionString = PublicLib.getStrConn();
            hsAdap.FillByHSTotNghiep(qLTH.tbl_HocSinh, idNamHoc);

            for (int i = 0; i < data.Rows.Count; i++)
            {
                int idHS = (int)data.Rows[i][0];

                for (int j = diemCol - 1; j < data.Columns.Count - 2; j++)
                {
                    DataRow[] hkRow = qLTH.qh_DiemTN.Select(qLTH.qh_DiemTN.idHocSinhColumn.ColumnName + "=" + idHS + 
                                                            " AND " + 
                                                            qLTH.qh_DiemTN.idMonHocColumn.ColumnName + "=" + lIdMonHoc[j - diemCol + 1] );
                    // save diem
                    if (hkRow.Length > 0)
                    {
                        if (data.Rows[i][j] != DBNull.Value) // HK 1
                            hkRow[0][qLTH.qh_DiemTN.DiemColumn] = data.Rows[i][j];
                        else
                            hkRow[0].Delete();
                    }
                    else
                    {
                        if (data.Rows[i][j] != DBNull.Value)
                        {
                            DataRow nRow = qLTH.qh_DiemTN.NewRow();

                            nRow[qLTH.qh_DiemTN.idHocSinhColumn] = idHS;
                            nRow[qLTH.qh_DiemTN.idMonHocColumn] = lIdMonHoc[j - diemCol + 1];
                            nRow[qLTH.qh_DiemTN.idNamHocColumn] = idNamHoc;
                            nRow[qLTH.qh_DiemTN.DiemColumn] = data.Rows[i][j];

                            qLTH.qh_DiemTN.Rows.Add(nRow);
                        }
                    }
                    #region Change flag - chi co tac dung khi nam hoc la nam dang thi
                    /*// change flag
                    DataRow[] t = qLTH.tbl_HocSinh.Select(qLTH.tbl_HocSinh.idColumn.ColumnName + "=" + idHS);
                    if ((int)data.Rows[i][data.Columns.Count - 1] == PConst.TN_KHONG_DU_DK)
                    {
                        DataRow[] tmp = dsNamToi.Select(dsNamToi.idHocSinhColumn.ColumnName + "=" + idHS);
                        if (tmp.Length == 0)
                        {
                            DataRow t = dsNamToi.NewRow();
                            t[dsNamToi.idHocSinhColumn] = idHS;
                            t[dsNamToi.idNamHocColumn] = idNamToi;
                            t[dsNamToi.KetQuaColumn] = DBNull.Value;
                            dsNamToi.Rows.Add(t);
                        }
                    }
                    else
                    {
                        // Doi Flag thanh "Da Tot Nghiep"
                        
                        if (t.Length > 0)
                            t[0][qLTH.tbl_HocSinh.FlagColumn] = PConst.FLAG_DA_TN;
                    }*/
                    #endregion
                }

                DataRow[] thiRow = qLTH.qh_DSThiTotNghiep.Select(qLTH.qh_DSThiTotNghiep.idHocSinhColumn.ColumnName + "=" + idHS);
                if (thiRow.Length > 0)
                {
                    thiRow[0][qLTH.qh_DSThiTotNghiep.KetQuaColumn] = data.Rows[i][data.Columns.Count - 1]; // Ket qua thi
                }
            }

            if (tscb_NamHoc.SelectedIndex == tscb_NamHoc.Items.Count - 2)
            {
                if (MessageBox.Show(MSG.MSG_CHUYEN_THI_TN, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    int idNamToi = (int)qLTH.tbl_NamHoc[tscb_NamHoc.SelectedIndex + 1][qLTH.tbl_NamHoc.idColumn];
                    MyDataSet.QLTH.qh_DSThiTotNghiepDataTable dsNamToi = new QLTH.qh_DSThiTotNghiepDataTable();
                    dsTN.FillByNamHoc(dsNamToi, idNamToi);

                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        int idHS = (int)data.Rows[i][0];
                        DataRow[] tt = qLTH.tbl_HocSinh.Select(qLTH.tbl_HocSinh.idColumn.ColumnName + "=" + idHS);

                        if ((int)data.Rows[i][data.Columns.Count - 1] == PConst.TN_KHONG_DU_DK)
                        {
                            DataRow[] tmp = dsNamToi.Select(dsNamToi.idHocSinhColumn.ColumnName + "=" + idHS);
                            if (tmp.Length == 0)
                            {
                                DataRow t = dsNamToi.NewRow();
                                t[dsNamToi.idHocSinhColumn] = idHS;
                                t[dsNamToi.idNamHocColumn] = idNamToi;
                                t[dsNamToi.KetQuaColumn] = DBNull.Value;
                                dsNamToi.Rows.Add(t);
                            }

                            if (tt.Length > 0)
                                tt[0][qLTH.tbl_HocSinh.FlagColumn] = PConst.FLAG_CHO_THI_TN;
                        }
                        else
                        {
                            // Doi Flag thanh "Da Tot Nghiep"
                            if (tt.Length > 0)
                                tt[0][qLTH.tbl_HocSinh.FlagColumn] = PConst.FLAG_DA_TN;
                        }
                    }

                    dsTN.Update(dsNamToi);
                    hsAdap.Update(qLTH.tbl_HocSinh);
                }
            }

            dsTN.Update(qLTH.qh_DSThiTotNghiep);
            diemAdap.Update(qLTH.qh_DiemTN);
            // -----------
        }

        private void tsb_Luu_Click(object sender, EventArgs e)
        {
            dg_DanhSach.EndEdit();
            saveData();
        }

        private void dg_DanhSach_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != dg_DanhSach.ColumnCount - 1)
            {
                calculateData();
            }
        }

        private void BangDiemTN_Activated(object sender, EventArgs e)
        {
            checkUserPower();
        }

        private void tsb_In_Click(object sender, EventArgs e)
        {
            PrintDataGrid.PrintDGV print = new PrintDataGrid.PrintDGV();
            print.Print_DataGridView(dg_DanhSach);
        }
    }
}
